<template>
    <NuxtLayout name="default">
        <div v-show="!firstLoading" class="chat-container">
            <template v-if="roomingLists.length > 0">
                <div class="side-employ-list">
                    <el-scrollbar class="flex-1 min-h-0">
                        <div class="px-3">
                            <div
                                v-for="(item, index) in roomingLists"
                                :key="index"
                                class="employ-item"
                                :class="roomingIndex === index ? 'active' : ''"
                                @click="handleChange(index)"
                            >
                                <photos width="30px" height="30px" radius="50%" :src="item.logo" />
                                <h5 class="flex-1 mx-2 font-medium line-clamp-1">{{ item.name }}</h5>
                                <el-popconfirm
                                    :hide-icon="true"
                                    width="230"
                                    confirm-button-text="删除"
                                    cancel-button-text="取消"
                                    icon-color="#626AEF"
                                    title="删除后无法恢复, 是否继续删除?"
                                    @confirm="handleDelete(index)"
                                >
                                    <template #reference>
                                        <icon name="el-icon-CircleClose" size="16" class="close"/>
                                    </template>
                                </el-popconfirm>
                            </div>
                            <div v-if="roomingLists.length === 0">
                                <el-empty
                                    class="mt-16"
                                    :image-size="80"
                                    description="暂无智能体"
                                />
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <chatting
                    :bot="roomingCode"
                    :ask="question"
                    :search="search"
                    :attach="attach"
                    :msg="msg"
                />
            </template>

            <diy-beauty
                v-else-if="diyData?.boards.style === 'beauty'"
                :robot-detail="robotDetail"
                @jump="handleJump"
                @search="(e: boolean) => search = e"
                @sending="sendChats"
            />

            <diy-simple
                v-else
                :robot-detail="robotDetail"
                @search="(e: boolean) => search = e"
                @sending="sendChats"
            />
        </div>
        <div class="text-center text-xs text-tx-placeholder pt-2.5">
            <!-- Unauthorized deletion or modification of redirect domain names is prohibited. -->
            <span>内容由 AI 生成，请仔细甄别</span>
            <nuxt-link v-if="restrict" to="https://www.mddai.cn">
                &nbsp;•&nbsp; Powered by www.mddai.cn
            </nuxt-link>
        </div>
    </NuxtLayout>
</template>

<script setup lang="ts">
import { diyEnum, popupEnum } from '~/enums/app'
import useAppStore from '~/stores/app'
import useUserStore from '~/stores/user'
import validateUtil from '~/utils/validate'
import chatRoomingApi from '~/api/agent/chat/rooming'
import Chatting from './_components/Chatting.vue'
import DiyBeauty from './_decoration/diy-beauty.vue'
import DiySimple from './_decoration/diy-simple.vue'

const router = useRouter()
const appStore = useAppStore()
const userStore = useUserStore()

const restrict = computed(() => appStore.getSwitchConfig.restrict)

// 默认智能体编号
const defaultRobot = computed(() => appStore.getDialogConfig.default_robot)
const robotDetail = ref({} as ChatRoomingInitResponse)

// 提问节点
const chatActionRef = shallowRef()
const question = ref<string>('')
const search = ref<boolean>(false)
const attach = ref<any[]>([])
const msg = ref<any[]>([])

// 首次加载
const firstLoading = ref<boolean>(true)

// 应用数据
const roomingCode = ref<string>('')
const roomingIndex = ref<number>(0)
const roomingLists = ref<ChatRoomingListResponse[]>([])

// 装修数据
const diyData = await appStore.getDiy(diyEnum.DESK)

/**
 * 链接跳转
 *
 * @param {string} type - 跳转类型
 * @param {string} layout - 布局方式
 * @param {any} row - 数据行
 * @author zero
 */
const handleJump = (type: string, layout: string, row: any) => {
    if (type === 'chat') {
        const content = layout === 'twig' ? row.intro : row.name
        chatActionRef.value?.setInputValue(content)
        question.value = content
    }
    if (!row.link?.path) {
        return
    }
    if (validateUtil.isExternal(row.link?.path)) {
        window.open(row.link?.path, '_blank')
    } else {
        router.push({
            path: row.link?.path,
            query: row.link?.query
        })
    }
}

/**
 * 发起对话
 *
 * @param {any} e
 * @param message
 * @param files
 * @author zero
 */
const sendChats = async (e?: string | Event, message?: any, files?: any) => {
    if (!defaultRobot.value) {
        return feedback.msgError('请在后台配置默认智能体')
    }

    let event
    if(e) {
        event = e as string
    }

    if (!userStore.isLogin) {
        return appStore.setPopup(popupEnum.LOGIN)
    }

    try {
        await chatRoomingApi.create(defaultRobot.value)
        await queryEmployList()
        question.value = event ?? question.value
        attach.value = files
        msg.value = message
    } catch {}
}

/**
 * 应用切换
 *
 * @param {number} index
 * @author zero
 */
const handleChange = (index: number) => {
    roomingIndex.value = index
    roomingCode.value = roomingLists.value[index]!.code
}

/**
 * 应用删除
 *
 * @param {number} index
 * @author zero
 */
const handleDelete = async (index: number) => {
    const botCode = roomingLists.value[index]!.code
    await chatRoomingApi.delete(botCode)
    await queryEmployList()
}

/**
 * 查应用列表
 *
 * @author zero
 */
const queryEmployList = async () => {
    if (userStore.isLogin) {
        roomingLists.value = await chatRoomingApi.lists()
        if (roomingLists.value.length > 0) {
            roomingCode.value = roomingLists.value[0]!.code
        }
    }
}

watch(
    () => defaultRobot.value,
    async (val: string) => {
        if (val && userStore.isLogin) {
            robotDetail.value = await chatRoomingApi.init(val)
        }
    }, { immediate: true }
)

onMounted(async () => {
    await queryEmployList()
    firstLoading.value = false
})
</script>

<style scoped lang="scss">
.chat-container {
    display: flex;
    height: 100%;
    overflow: hidden;
    background-color: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    .side-employ-list {
        display: flex;
        flex-direction: column;
        width: 240px;
        overflow: hidden;
        border-right: 1px solid var(--el-border-color-lighter);
        .employ-item {
            position: relative;
            display: flex;
            align-items: center;
            padding: 6px 8px;
            margin: 10px 0;
            color: var(--el-text-color-regular);
            cursor: pointer;
            background-color: var(--el-bg-color-light);
            border: 1px solid var(--el-bg-color-light);
            border-radius: 8px;
            .el-dropdown-link {
                visibility: hidden;
            }
            &.active {
                color: var(--el-color-primary);
                border-color: var(--el-color-primary-light-3);
            }
            &:hover {
                &:not(.active) {
                    background-color: var(--el-bg-color-light);
                    border-color: var(--el-color-primary-light-3);
                }
                .el-dropdown-link {
                    visibility: visible;
                }
                .close { display: block; }
            }
            .close {
                z-index: 9999;
                display: none;
                color: var(--el-text-color-placeholder);
                &:hover { color: var(--el-color-error); }
            }
        }
    }
}
</style>
